package cn.itsource.hrm.consumer;

import cn.itsource.hrm.to.EmailSendTo;
import cn.itsource.hrm.to.SMSSendTo;
import cn.itsource.hrm.to.SystemMessageSendTo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;


import java.io.IOException;
import java.util.List;

import static cn.itsource.hrm.constants.MQConstants.*;

//消费者
@Component
@Slf4j
public class Consumer {

    //短信消费
    @RabbitListener(queues = QUEUE_NAME_SMS)
    public void getPhones(@Payload SMSSendTo smsSendTo, Message message, Channel channel){
            if(smsSendTo!=null){
                String content = smsSendTo.getContent();
                List<String> phones = smsSendTo.getPhones();
                for (String phone : phones) {
                    log.info("短信发送，手机:{} ,内容：{}",phone,content);
                }
                //手动签收
                ack(message, channel);
            }
    }
    //邮件消费
    @RabbitListener(queues = QUEUE_NAME_EMAIL)
    public void getEamil(@Payload EmailSendTo emailSendTo, Message message, Channel channel){
        if(emailSendTo!=null){
            String content = emailSendTo.getContent();
            List<String> emails = emailSendTo.getEmails();
            for (String email : emails) {
                log.info("邮件发送，邮箱:{} ,内容：{}",email,content);
            }
            //手动签收
            ack(message, channel);
        }
    }
    //站内信消费
    @RabbitListener(queues = QUEUE_NAME_SYSTEM_MESSAGE)
    public void getSystem(@Payload SystemMessageSendTo systemMessageSendTo, Message message, Channel channel){
        if(systemMessageSendTo!=null){
            String content = systemMessageSendTo.getContent();
            List<Long> userIds = systemMessageSendTo.getUserIds();
            for (Long userId : userIds) {
                log.info("站内信发送，用户:{} ,内容：{}",userId,content);
            }
            //手动签收
            ack(message, channel);
        }
    }

    //签收消息
    private void ack(Message message, Channel channel) {
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
